<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@include file="../connstring.jsp" %>
<%
request.setCharacterEncoding("UTF-8");
String strYhm=request.getParameter("username");
String strMm=request.getParameter("password");
if(strYhm==null) strYhm="";
if(strMm==null) strMm="";
if(strYhm.trim().equals("")||strMm.trim().equals("")){
%>	
<script type="text/javascript">
 alert("用户名或密码为空！请重试。");
 history.go(-1);
 </script>

<%
}else{

    // 获取表单数据
    request.setCharacterEncoding("UTF-8");
    String us = request.getParameter("username");
    String pa = request.getParameter("password");

    // 数据库连接信息


    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        // 连接数据库
        Class.forName(driver);
        conn = DriverManager.getConnection(url);

        // 插入记录，使用 PreparedStatement 对占位符进行绑定，避免 SQL 注入攻击
        String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, us);
        pstmt.setString(2, pa);
        pstmt.executeUpdate();

        // 查询记录
        sql = "SELECT * FROM user";
        rs = pstmt.executeQuery();
        // 处理查询结果
        while (rs.next()) {
            // 处理数据
             out.print(rs.getInt("id") + "\t");
               out.print(rs.getString("username") + "\t");
               out.println(rs.getString("password") + "\t");
           
        }
    } catch (SQLException e) {
        // 处理异常
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // 处理异常
        e.printStackTrace();
    } finally {
        // 关闭连接和资源
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    response.sendRedirect("userlist.jsp");
}
%>